#!/usr/bin/python
import urllib
import simplejson

class UrlShortener:
    """Interface for all url shorteners"""
    # key: string
    # maxSize
    # minSize
    # def __call__(self, url):
    #     return short-url

class SimpleUrlShortener(UrlShortener):
    # Must define encodingUrl
    def __call__(self, url):
        encodedurl = self.encodingUrl + urllib.urlencode({"url":url})
        instream=urllib.urlopen(encodedurl)
        tinyurl=instream.read()
        instream.close()
        return tinyurl

class TinyUrlShortener(SimpleUrlShortener):
    key = "tinyUrl"
    minSize = len("http://tinyurl.com/1c2")
    maxSize = len("http://tinyurl.com/2hzczc")
    encodingUrl = "http://tinyurl.com/api-create.php?"

class BitLyShortener(UrlShortener):
    key = "bitly"
    minSize = ""
    maxSize = ""

    def __init__(self, login, apiKey, domain="bit.ly"):
        self.login = login
        self.apiKey= apiKey
        self.domain = domain

    def _call(self, url):
        request = "http://api.%s/shorten?version=2.0.1&longUrl=" % self.domain
        request += url
        request += "&login=" + self.login + "&apiKey=" +self.apiKey
        result = urllib.urlopen(request)
        json = simplejson.loads(result.read())
        # Sample result
        # {u'errorCode': 0, u'errorMessage': u'', u'results': {u'http://instafeed.net': {u'shortKeywordUrl': u'', 
        #  u'hash': u'sON0R', u'userHash': u'dpW0r', u'shortUrl': u'http://bit.ly/dpW0r'}}, u'statusCode': u'OK'}
        if json["errorCode"] != 0:
            raise RuntimeError("Error shortening url with bit.ly: %s" % json)
        return json["results"][url]["shortUrl"]

    def __call__(self, url):
        try:
            return self._call(url)
        except ValueError:
            # Sometimes bitly returns an invalid page and simplejson throws "ValueError", we sleep 1s and try again
            import time
            time.sleep(1)
            return self._call(url)


if __name__ == "__main__":
    import sys
    print TinyUrlShortener()(sys.argv[1])

    #BitLyShortener()
